<!-- 编辑弹窗 -->
<template>
  <ele-modal
    form
    destroy-on-close
    :width="740"
    v-model="visible"
    :title="actionConfigs[action].title"
    @open="handleOpen"
    @close="handleCancel"
  >
    <el-form
      ref="formRef"
      :model="form"
      :rules="currentRules"
      label-width="100px"
      :validate-on-rule-change="false"
      @submit.prevent=""
    >
      <el-row :gutter="16">
        <el-col :sm="12" :xs="24">
          <el-form-item label="上级菜单" prop="parent_id">
            <menu-select ref="menuSelectRef" v-model="form.parent_id" />
          </el-form-item>
          <el-form-item label="菜单名称" prop="title">
            <el-input
              clearable
              :maxlength="20"
              v-model="form.title"
              placeholder="请输入菜单名称"
            />
          </el-form-item>
        </el-col>
        <el-col :sm="12" :xs="24">
          <el-form-item label="菜单类型" prop="menu_type">
            <el-radio-group
              v-model="form.menu_type"
              @change="handleMenuTypeChange"
            >
              <el-radio :value="0" label="目录" />
              <el-radio :value="1" label="菜单" />
              <el-radio :value="2" label="按钮" />
            </el-radio-group>
          </el-form-item>
          <el-form-item label="打开方式">
            <el-radio-group
              v-model="form.openType"
              :disabled="form.menu_type === 0 || form.menu_type === 2"
              @change="handleOpenTypeChange"
            >
              <el-radio :value="0" label="组件" />
              <el-radio :value="1" label="内嵌" />
              <el-radio :value="2" label="外链" />
            </el-radio-group>
          </el-form-item>
        </el-col>
      </el-row>
      <el-divider style="margin: 8px 0 22px 0; opacity: 0.6" />
      <el-row :gutter="16">
        <el-col :sm="12" :xs="24">
          <el-form-item label="菜单图标" prop="icon">
            <icon-select
              clearable
              filterable="popper"
              :popper-width="460"
              :popper-height="388"
              :popper-options="{ strategy: 'fixed' }"
              placeholder="请选择图标"
              v-model="form.icon"
              :disabled="form.menu_type === 2"
            />
          </el-form-item>
          <el-form-item prop="path">
            <template #label>
              <ele-tooltip
                v-if="form.openType === 2"
                content="需要以`http://`、`https://`、`//`开头"
                placement="top-start"
                :popper-options="{
                  modifiers: [
                    { name: 'offset', options: { offset: [-12, 10] } },
                  ],
                }"
              >
                <el-icon
                  :size="15"
                  style="align-self: center; margin-right: 4px; cursor: help"
                >
                  <QuestionCircleOutlined style="opacity: 0.6" />
                </el-icon>
              </ele-tooltip>
              <span>{{ form.openType === 2 ? "外链地址" : "路由地址" }}</span>
            </template>
            <el-input
              clearable
              :maxlength="100"
              v-model="form.path"
              :disabled="form.menu_type === 2"
              :placeholder="
                form.openType === 2 ? '请输入外链地址' : '请输入路由地址'
              "
            />
          </el-form-item>
          <el-form-item prop="component">
            <template #label>
              <ele-tooltip
                v-if="form.openType === 1"
                content="需要以`http://`、`https://`、`//`开头"
                placement="top-start"
                :popper-options="{
                  modifiers: [
                    { name: 'offset', options: { offset: [-12, 10] } },
                  ],
                }"
              >
                <el-icon
                  :size="15"
                  style="align-self: center; margin-right: 4px; cursor: help"
                >
                  <QuestionCircleOutlined style="opacity: 0.6" />
                </el-icon>
              </ele-tooltip>
              <span>{{ form.openType === 1 ? "内嵌地址" : "组件路径" }}</span>
            </template>
            <el-input
              clearable
              :maxlength="100"
              v-model="form.component"
              :disabled="
                form.menu_type === 0 ||
                form.menu_type === 2 ||
                form.openType === 2
              "
              :placeholder="
                form.openType === 1 ? '请输入内嵌地址' : '请输入组件路径'
              "
            />
          </el-form-item>
        </el-col>
        <el-col :sm="12" :xs="24">
          <el-form-item label="权限标识" prop="authority">
            <el-input
              clearable
              v-model="form.authority"
              placeholder="请输入权限标识"
              :disabled="
                form.menu_type === 0 ||
                (form.menu_type === 1 && form.openType === 2)
              "
            />
          </el-form-item>
          <el-form-item label="排序号" prop="sort_number">
            <el-input-number
              :min="0"
              :max="99999"
              v-model="form.sort_number"
              placeholder="请输入排序号"
              controls-position="right"
              class="ele-fluid"
            />
          </el-form-item>
          <el-form-item label="是否展示">
            <el-switch
              inline-prompt
              active-text="是"
              inactive-text="否"
              :model-value="form.hide === 0"
              :disabled="form.menu_type === 2"
              @change="updateHideValue"
            />
            <ele-tooltip
              content="选择不展示只注册路由不展示在侧边栏, 比如添加页面应该选择不展示"
              :popper-style="{ maxWidth: '240px' }"
            >
              <el-icon :size="15" style="margin-left: 16px; cursor: help">
                <QuestionCircleOutlined style="opacity: 0.6" />
              </el-icon>
            </ele-tooltip>
          </el-form-item>
        </el-col>
      </el-row>
      <el-form-item label="路由元数据" prop="meta">
        <el-input
          :rows="4"
          type="textarea"
          :maxlength="200"
          v-model="form.meta"
          placeholder="请输入JSON格式的路由元数据"
        />
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="resetForm">重置</el-button>
      <el-button @click="handleCancel">取消</el-button>
      <el-button type="primary" :loading="loading" @click="handleSubmit">
        {{ actionConfigs[action].button }}
      </el-button>
    </template>
  </ele-modal>
</template>

<script setup>
import { ref, computed } from "vue";
import { isExternalLink } from "ele-admin-plus/es";
import { QuestionCircleOutlined } from "@/components/icons";
// import { useFormData } from "@/utils/use-form-data";
import IconSelect from "@/components/IconSelect/index.vue";
import MenuSelect from "./menu-select.vue";
import { addMenu, updateMenu, getMenu } from "@/api/system/menu";
import { useFormEdit } from "@/hooks/useFormEdit";
/** 菜单下拉选择组件 */
const menuSelectRef = ref(null);
const props = defineProps({
  /** 修改回显的数据 */
  data: Object,
  action: {
    type: String,
    default: "edit",
    validator: (value) => ["add", "edit", "view"].includes(value),
  },
  parentMenuType: [Number, String], // 修改为接受数字或字符串
  parentId: Number, // 接收parent_id
});

const emit = defineEmits(["update:modelValue", "done", "open"]);

// /** 弹窗是否打开 */
// const visible = defineModel({ type: Boolean });

// /** 提交状态 */
// const loading = ref(false);

// /** 表单实例 */
// const formRef = ref(null);

// /** 表单数据 */
// const [form, resetFields, assignFields] = useFormData({
//   menu_id: void 0,
//   parent_id: void 0,
//   title: "",
//   menu_type: 0,
//   openType: 0,
//   icon: "",
//   path: "",
//   component: "",
//   authority: "",
//   sort_number: void 0,
//   hide: 0,
//   meta: "",
// });

// /** 表单验证规则 */
// const rules = computed(() => {
//   console.log("form", form); // 打印form的值，确保它是响应式的
//   const obj = {
//     title: [
//       {
//         required: true,
//         type: "string",
//         message: "请输入菜单名称",
//         trigger: "blur",
//       },
//     ],
//     sort_number: [
//       {
//         required: true,
//         type: "number",
//         message: "请输入排序号",
//         trigger: "blur",
//       },
//     ],
//     meta: [
//       {
//         type: "string",
//         validator: (_rule, value, callback) => {
//           if (value) {
//             const msg = "请输入正确的JSON格式";
//             try {
//               const obj = JSON.parse(value);
//               if (obj == null || typeof obj !== "object") {
//                 callback(msg);
//                 return;
//               }
//             } catch (_e) {
//               callback(msg);
//               return;
//             }
//           }
//           callback();
//         },
//         trigger: "blur",
//       },
//     ],
//   };
//   if (form.menu_type !== 2) {
//     obj.path = [
//       {
//         required: true,
//         type: "string",
//         message: form.openType === 2 ? "请输入外链地址" : "请输入路由地址",
//         trigger: "blur",
//       },
//       {
//         type: "string",
//         validator: (_rule, value, callback) => {
//           if (value) {
//             if (form.openType === 2) {
//               if (!isExternalLink(value)) {
//                 callback("请输入正确的链接地址");
//                 return;
//               }
//             } else {
//               if (value === "/") {
//                 callback("路由地址不能为 /");
//                 return;
//               }
//               if (!value.startsWith("/")) {
//                 callback("路由地址需要以 / 开头");
//                 return;
//               }
//             }
//           }
//           callback();
//         },
//         trigger: "blur",
//       },
//     ];
//     if (form.menu_type === 1 && form.openType !== 2) {
//       obj.component = [
//         {
//           required: true,
//           type: "string",
//           message: form.openType === 1 ? "请输入内嵌地址" : "请输入组件路径",
//           trigger: "blur",
//         },
//         {
//           type: "string",
//           validator: (_rule, value, callback) => {
//             if (value) {
//               if (form.openType === 1) {
//                 if (!isExternalLink(value)) {
//                   callback("请输入正确的链接地址");
//                   return;
//                 }
//               }
//             }
//             callback();
//           },
//           trigger: "blur",
//         },
//       ];
//     }
//   }
//   return obj;
// });

// /** 关闭弹窗 */
// const handleCancel = () => {
//   visible.value = false;
// };

// /** 保存编辑 */
// const save = () => {
//   formRef.value?.validate?.((valid) => {
//     if (!valid) {
//       return;
//     }
//     loading.value = true;
//     const saveOrUpdate = isUpdate.value ? updateMenu : addMenu;
//     saveOrUpdate({
//       ...form,
//       // menu_type 对应的值与后端不一致在前端处理
//       menu_type: form.menu_type === 2 ? 1 : 0,
//       parent_id: form.parent_id || 0,
//     })
//       .then((msg) => {
//         loading.value = false;
//         EleMessage.success(msg);
//         handleCancel();
//         emit("done");
//       })
//       .catch((e) => {
//         loading.value = false;
//         EleMessage.error(e.message);
//       });
//   });
// };

/** menuType选择改变 */
const handleMenuTypeChange = () => {
  if (form.menu_type === 0) {
    form.authority = "";
    form.openType = 0;
    form.component = "";
  } else if (form.menu_type === 1) {
    if (form.openType === 2) {
      form.authority = "";
    }
  } else {
    form.openType = 0;
    form.icon = "";
    form.path = "";
    form.component = "";
    form.hide = 0;
  }
  formRef.value?.clearValidate?.();
};

/** openType选择改变 */
const handleOpenTypeChange = () => {
  if (form.openType === 2) {
    form.component = "";
    form.authority = "";
  }
  formRef.value?.clearValidate?.();
};

/** hide选择改变 */
const updateHideValue = (value) => {
  form.hide = value ? 0 : 1;
};

/** 判断是否是目录 */
const isDirectory = (d) => {
  return !!d.children?.length && !d.component;
};

// /** 弹窗打开事件 */
// const handleOpen = () => {
//   if (props.data) {
//     const isExternal = isExternalLink(props.data.path);
//     const isInner = isExternalLink(props.data.component);
//     // menuType对应的值与后端不一致在前端处理
//     const menu_type =
//       props.data.menu_type === 1 ? 2 : isDirectory(props.data) ? 0 : 1;
//     assignFields({
//       ...props.data,
//       menu_type,
//       openType: isExternal ? 2 : isInner ? 1 : 0,
//       parent_id: props.data.parent_id === 0 ? void 0 : props.data.parent_id,
//     });
//     isUpdate.value = true;
//   } else {
//     resetFields();
//     form.parent_id = props.parent_id;
//     isUpdate.value = false;
//   }
//   nextTick(() => {
//     nextTick(() => {
//       formRef.value?.clearValidate?.();
//     });
//   });
// };

/** 刷新菜单下拉选择数据 */
const reloadMenuSelectData = () => {
  console.log("menuSelectRef", menuSelectRef.value); // 打印menuSelectRef的值
  menuSelectRef.value?.reload?.();
};

defineExpose({ reloadMenuSelectData });

const actionConfigs = {
  add: {
    title: "新增菜单",
    button: "新增",
    api: addMenu,
    showFields: [],
    disabledFields: [],
    rules: computed(() => {
      const obj = {
        title: [
          {
            required: true,
            type: "string",
            message: "请输入菜单名称",
            trigger: "blur",
          },
        ],
        sort_number: [
          {
            required: true,
            type: "number",
            message: "请输入排序号",
            trigger: "blur",
          },
        ],
        meta: [
          {
            type: "string",
            validator: (_rule, value, callback) => {
              if (value) {
                const msg = "请输入正确的JSON格式";
                try {
                  const obj = JSON.parse(value);
                  if (obj == null || typeof obj !== "object") {
                    callback(msg);
                    return;
                  }
                } catch (_e) {
                  callback(msg);
                  return;
                }
              }
              callback();
            },
            trigger: "blur",
          },
        ],
      };
      if (form.menu_type !== 2) {
        obj.path = [
          {
            required: true,
            type: "string",
            message: form.openType === 2 ? "请输入外链地址" : "请输入路由地址",
            trigger: "blur",
          },
          {
            type: "string",
            validator: (_rule, value, callback) => {
              if (value) {
                if (form.openType === 2) {
                  if (!isExternalLink(value)) {
                    callback("请输入正确的链接地址");
                    return;
                  }
                } else {
                  if (value === "/") {
                    callback("路由地址不能为 /");
                    return;
                  }
                  if (!value.startsWith("/")) {
                    callback("路由地址需要以 / 开头");
                    return;
                  }
                }
              }
              callback();
            },
            trigger: "blur",
          },
        ];
        if (form.menu_type === 1 && form.openType !== 2) {
          obj.component = [
            {
              required: true,
              type: "string",
              message:
                form.openType === 1 ? "请输入内嵌地址" : "请输入组件路径",
              trigger: "blur",
            },
            {
              type: "string",
              validator: (_rule, value, callback) => {
                if (value) {
                  if (form.openType === 1) {
                    if (!isExternalLink(value)) {
                      callback("请输入正确的链接地址");
                      return;
                    }
                  }
                }
                callback();
              },
              trigger: "blur",
            },
          ];
        }
      }
      return obj;
    }),
    beforeOpen: ({ type, formData }) => {
      // 打开前的操作，可以修改表单数据
      formData.parent_id = props.parentId; // 使用props.organizationId初始化
      console.log("打开前的数据:", props);
      if (props.parentMenuType !== "") {
        formData.menu_type = props.parentMenuType + 1; // 使用props.organizationId初始化
      }
      formData.menu_type = formData.menu_type >= 2 ? 2 : formData.menu_type; // 使用props.organizationId初始化
      if (formData.menu_type === undefined) {
        formData.menu_type = 0; // 使用props.organizationId初始化
      }
      console.log("打开前的数据:", formData);
      return { type, formData }; // 必须返回处理后的表单数据
    },
    afterOpen: async (form, formData) => {
      assignFields({ ...form, ...formData });
      return form;
    },
    beforeSubmit: async ({ type, formData }) => {
      // 提交前的操作，可以修改表单数据
      console.log("提交数据:", formData);
      // if (!formData.requiredField) {
      //   return Promise.reject(new Error("缺少必填字段")); // 返回rejected Promise中断流程
      // }
      return { type, formData }; // 必须返回处理后的表单数据
    },
  },
  edit: {
    title: "修改菜单",
    button: "修改",
    api: updateMenu, // 补充edit的API
    showFields: [],
    disabledFields: [],
    rules: computed(() => {
      console.log("编辑规则:", form); // 打印编辑规则，检查是否正确设置了必填项和其他规则
      const obj = {
        title: [
          {
            required: true,
            type: "string",
            message: "请输入菜单名称",
            trigger: "blur",
          },
        ],
        sort_number: [
          {
            required: true,
            type: "number",
            message: "请输入排序号",
            trigger: "blur",
          },
        ],
        meta: [
          {
            type: "string",
            validator: (_rule, value, callback) => {
              if (value) {
                const msg = "请输入正确的JSON格式";
                try {
                  const obj = JSON.parse(value);
                  if (obj == null || typeof obj !== "object") {
                    callback(msg);
                    return;
                  }
                } catch (_e) {
                  callback(msg);
                  return;
                }
              }
              callback();
            },
            trigger: "blur",
          },
        ],
      };
      if (form.menu_type !== 2) {
        obj.path = [
          {
            required: true,
            type: "string",
            message: form.openType === 2 ? "请输入外链地址" : "请输入路由地址",
            trigger: "blur",
          },
          {
            type: "string",
            validator: (_rule, value, callback) => {
              if (value) {
                if (form.openType === 2) {
                  if (!isExternalLink(value)) {
                    callback("请输入正确的链接地址");
                    return;
                  }
                } else {
                  if (value === "/") {
                    callback("路由地址不能为 /");
                    return;
                  }
                  if (!value.startsWith("/")) {
                    callback("路由地址需要以 / 开头");
                    return;
                  }
                }
              }
              callback();
            },
            trigger: "blur",
          },
        ];
        if (form.menu_type === 1 && form.openType !== 2) {
          obj.component = [
            {
              required: true,
              type: "string",
              message:
                form.openType === 1 ? "请输入内嵌地址" : "请输入组件路径",
              trigger: "blur",
            },
            {
              type: "string",
              validator: (_rule, value, callback) => {
                if (value) {
                  if (form.openType === 1) {
                    if (!isExternalLink(value)) {
                      callback("请输入正确的链接地址");
                      return;
                    }
                  }
                }
                callback();
              },
              trigger: "blur",
            },
          ];
        }
      }
      console.log("编辑规则:", obj); // 打印编辑规则，检查是否正确设置了必填项和其他规则
      return obj;
    }),

    beforeOpen: ({ type, formData }) => {
      const isExternal = isExternalLink(props.data.path);
      const isInner = isExternalLink(props.data.component);
      //     // menuType对应的值与后端不一致在前端处理
      const menu_type =
        props.data.menu_type === 2 ? 2 : isDirectory(props.data) ? 0 : 1;
      console.log(
        props.data.path,
        "isExternal:",
        isExternal,
        props.data.component,
        "isInner",
        isInner,
        "menu_type",
        menu_type,
        " props.data.menu_type",
        props.data.menu_type,
        isDirectory(props.data),
      ); // 打印openType的值，检查是否正确设置了必填项和其他规则
      formData.menu_type = menu_type; // 确保menu_type的值正确设置
      formData.openType = isExternal ? 2 : isInner ? 1 : 0; // 确保openType的值正确设置
      formData.parent_id =
        props.data.parent_id === 0 ? void 0 : props.data.parent_id; // 确保parent_id的值正确设置

      return { type, formData }; // 必须返回处理后的表单数据
    },
  },
  view: {
    title: "查看菜单",
    button: "确定",
    // api: showDictionaryData, // 补充view的API
    showFields: [],
    disabledFields: [],
    rules: {},
  },
};
console.log("parent_id", props.parent_id);

const {
  form,
  resetForm,
  formRef,
  visible,
  loading,
  handleOpen,
  handleSubmit,
  currentRules,
  handleCancel,
  assignFields,
} = useFormEdit(props, emit, {
  actionConfigs,
  formFields: {
    parent_id: props.parentId || undefined, // 使用props.organizationId初始化
    menu_id: void 0,
    title: "",
    menu_type: 0,
    openType: 0,
    icon: "",
    path: "",
    component: "",
    authority: "",
    sort_number: void 0,
    hide: 0,
    meta: "",
  },
  detailApi: getMenu,
  idField: "menu_id",
});
</script>
